package com.dmcb.trade.business.crawlers.author;

import com.dmcb.common.business.constants.CommonConstant;
import com.dmcb.common.business.utils.JsonUtil;
import com.dmcb.common.business.utils.ListUtil;
import com.dmcb.common.business.utils.WebUtil;
import com.dmcb.common.web.conversion.JsonResult;
import com.dmcb.trade.business.constants.CrawlConstant;
import com.dmcb.trade.business.crawlers.article.PencilNewsParser;
import com.dmcb.trade.business.entities.Article;
import com.dmcb.trade.business.entities.Author;
import com.dmcb.trade.business.mappers.ArticleCrawlMapper;
import org.jsoup.nodes.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * 铅笔道文章解析
 * Created by 黑米 on 2017/3/15.
 */
@Service
public class QianBiDaoCrawler extends BaseCrawler {
    Logger logger = LoggerFactory.getLogger(JianshuCrawler.class);

    @Autowired
    private PencilNewsParser pencilNewsParser;
    @Autowired
    private ArticleCrawlMapper articleCrawlMapper;

    @Override
    protected String url() {
        return CrawlConstant.QIANBIDAO_URL;
    }

    @Override
    protected int tag() {
        return CrawlConstant.QIANBIDAO_TAG;
    }

    @Override
    protected String avatarSelect() {
        return "a.avatar>img";
    }

    @Override
    protected String channelNameSelect() {
        return "div.title>a";
    }

    /**
     * 频道名称是否同时是作者名称
     *
     * @return 是、否
     */
    @Override
    protected boolean isAuthorName() {
        return false;
    }

    @Override
    protected String listSelect() {
        return "ul.note-list>li";
    }

    @Override
    protected String titleSelect() {
        return "div.content>a";
    }

    @Override
    protected String authorSelect() {
        return "div.title>a";
    }

    @Override
    protected String authorLink() {
        return null;
    }

    //https://api.pencilnews.cn/articles?page=1&page_size=20&industry_id=&cate_id=1&journalist_id=&time_start=&stage_id=&keyword=
    //https://api.pencilnews.cn/articles?page=1&page_size=20&industry_id=&cate_id=2&journalist_id=&time_start=&stage_id=&keyword=
    //https://api.pencilnews.cn/articles?page=1&page_size=20&industry_id=&cate_id=3

    public List<Map<String, Object>> geList(String json) {
        Map<String, Object> map = JsonUtil.getResult(json);
        if (map == null || map.size() == 0) {
            return null;
        }
        map = (Map) map.get("data");
        if (map == null || map.size() == 0) {
            return null;
        }
        List<Map<String, Object>> mapList = (List) map.get("articles");
        return mapList;
    }

    @Override
    protected JsonResult crawl(int authorId, String link, Author author, Document doc, boolean all) {
        // 爬取文章
        int page = 0;
        int totalAll = 0;
        for (int i = 1; i < 4; i++) {
            System.out.print("https://api.pencilnews.cn/articles?page=" + page + "&page_size=20&industry_id=&cate_id=" + i + "&journalist_id=&time_start=&stage_id=&keyword=");
            while (page <= CrawlConstant.CRAWL_PAGE_TOTAL) {
                String json = WebUtil.buildRequestIgnoreSSL("https://api.pencilnews.cn/articles?page=" + page + "&page_size=20&industry_id=&cate_id=" + i + "&journalist_id=&time_start=&stage_id=&keyword=");
                List<Map<String, Object>> mapList = geList(json);
                if (ListUtil.isEmpty(mapList)) {
                    continue;
                }
                JsonResult result = iterate(authorId, mapList);
                if (!result.isSuccess()) {
                    return result;
                }
                totalAll += result.getInt();
                if (!all && result.getInt() < 1) {
                    break;
                }
                page++;
            }
        }
        return totalAll == 0 ? error(CrawlConstant.MSG_WARN_NO_UPDATE) : success(totalAll);
    }

    /**
     * 迭代解析、保存文章
     *
     * @return 成功保存数量
     */
    protected JsonResult iterate(int authorId, List<Map<String, Object>> mapList) {

        int succ = 0;
        int exist = 0;
        for (Map<String, Object> map : mapList) {
            // 获取标题、链接元素
            map = (Map) map.get("article_info");
            String title = (String) map.get("title");
            if (title != null) {
                try {
                    // 校验作者、标题是否已存在
                    Article article = articleCrawlMapper.queryByAuthorTitle(authorId, title.trim());
                    if (article != null) {
                        exist++;
                        if (exist >= 6 && succ == 0) {
                            return success(0);
                        }
                        continue;
                    }
                    Integer id = (Integer) map.get("article_id");
                  String  href = "https://www.pencilnews.cn/p/" + id + ".html";
                    JsonResult result = parse(authorId, href);
                    succ += result.isSuccess() ? 1 : 0;
                } catch (Exception e) {
                    logger.error("Parser.parse error,{}", title, e);
                    return error(CommonConstant.ABNORMAL_MSG);
                }
            }
        }
        return success(succ);
    }


    @Override
    protected JsonResult parse(int authorId, String link) throws Exception {
        return pencilNewsParser.parse(authorId, link);
    }

    @Override
    protected String getBody(Document doc) {
        return pencilNewsParser.getBody(doc);
    }
}

